<template>
  <div>
    <el-row>
      <el-col :span="12">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span>使用的工作日历</span>
            <div class="app-container1">
              <el-calendar v-model="value" >
              <template
    slot="dateCell"
    slot-scope="{date, data}">
    <p :class="data.isSelected ? 'is-selected' : ''">
      {{ data.day.split('-').slice(2).join().replace(/\b(0+)/gi,"") }}
    </p>
       <div v-if="special(data.day) == 1" class="red budge"></div>
      <div v-if="special(data.day) == 2 " class="green budge"></div>
                           

  </template>  
              </el-calendar>
            </div>
          </div>
           <div>
          <el-row>
                <el-col :span="4"> <div class="red budge"></div></el-col> <el-col :span="8">例外工作日</el-col>
                <el-col :span="4"><div class="green budge"></div></el-col> <el-col :span="8">例外休息日</el-col>
          </el-row>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12" style="float:right;">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-button-group style="float: right">
              <el-button
                type="primary"
                icon="el-icon-plus"
                class="el-button--mini"
                @click="handleCreate"
                >添加</el-button
              >
              <el-button type="primary"
              icon="el-icon-edit"
               size="mini" @click="handleUpdate()">
                编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                 icon="el-icon-delete"
                @click="ui_delete(null, null)"
              >
                删除
              </el-button>
            </el-button-group>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row>
      <div class="app-container">
        <el-row type="flex" justify="start">
          <el-table
            v-loading="listLoading"
            :data="list"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            @row-click="rowClick"
            @selection-change="handleSelectionChange"
          >
            >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column
              align="center"
              label="日历名称"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.calendarName }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="日历类型"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.calendarTypeName }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="月份"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.yearMonth }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="工作日"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.workDays | workdays}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="工作日小时"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.workHours }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="是否自定义"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.customed == false? '否': '是' }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="周一"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.monday }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="周二"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.tuesday }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="周三"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.wensday }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="周四"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.thursday }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="周五"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.friday }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="周六"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.saturday }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="周天"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.sunday }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="例外工作日"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.specialWorkDays }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="例外工作日备注"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.commentWork }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="例外休息日"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.specialRestDays }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="例外休息日备注"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.commentRest }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="是否已删除"
              width="95"
              style="display:none;"
              v-if="false"
            >
              <template slot-scope="scope">
                {{ scope.row.isdeleted }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="状态"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.status  }}
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </div>
    </el-row>
     <el-row>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        :page-sizes="listQuery.pageSizes"
        @pagination="fetchData"
      />
    </el-row>
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
       width="1000px"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        size="small"
      >
        <el-row>
          <el-col :span="12">
            <el-row>
              <el-col :span="12">
                <el-form-item label="日历名称" prop="calendarName">
                  <el-input v-model="temp.calendarName" /> </el-form-item
              ></el-col>
              <el-col :span="12">
                <el-form-item label="日历类型" prop="calendarTypeId">
                  <el-select v-model="temp.calendarTypeId" placeholder="请选择日历类型" style="width:120px;">
                    <el-option v-for="itm in this.ddCalendarTypes" :label="itm.label" :value="itm.value" :key="itm.value">
                    </el-option>
                  </el-select> 

                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="月份" prop="yearMonth">
                  <el-date-picker v-model="temp.yearMonth" placeholder="请选择月份" type="month"  style="width:120px;" value-format="yyyy-MM"></el-date-picker></el-form-item
              ></el-col>
              <el-col :span="12">
                <el-form-item label="工作日" prop="workDays">
                 <el-select v-model="temp.workDays" placeholder="请选择工作日类型" style="width:120px;">
                    <el-option v-for="itm in this.ddWorkDays" :label="itm.label" :value= itm.value :key=itm.value >
                    </el-option>
                  </el-select> 
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="工作日小时" prop="workHours">
                  <el-input v-model="temp.workHours" /> </el-form-item
              ></el-col>
              <el-col :span="12">
                <el-form-item label="" prop="customed">
                  <el-button type="primary" size="mini" @click="handleCustomed()">
                    自定义
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
            <div class="wrapperSon" v-if="this.temp.customed">
              <el-form-item label="周一" prop="monday" size="mini">
                <el-input v-model="temp.monday" />
              </el-form-item>
              <el-form-item label="周二" prop="tuesday"  size="mini">
                <el-input v-model="temp.tuesday" />
              </el-form-item>
              <el-form-item label="周三" prop="wensday"  size="mini">
                <el-input v-model="temp.wensday" />
              </el-form-item>
              <el-form-item label="周四" prop="thursday"  size="mini">
                <el-input v-model="temp.thursday" />
              </el-form-item>
              <el-form-item label="周五" prop="friday"  size="mini">
                <el-input v-model="temp.friday" />
              </el-form-item>
              <el-form-item label="周六" prop="saturday"  size="mini">
                <el-input v-model="temp.saturday" />
              </el-form-item>
              <el-form-item label="周天" prop="sunday"  size="mini">
                <el-input v-model="temp.sunday" />
              </el-form-item>
            </div>
              </el-row>
          </el-col>
          <el-col :span="12">
            <el-row>
              <el-button-group style="float: left;">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  class="el-button--mini"
                  @click="handleCreate"
                  >新建日历</el-button
                >

                <el-button
                  size="mini"
                  type="danger"
                   icon="el-icon-delete"
                  @click="ui_delete(null, null)"
                >
                  删除日历
                </el-button>
              </el-button-group>
              </el-row>
             <el-row>
               <el-col :span="12"> <span>选择例外工作日</span></el-col>
                   <el-col :span="12"><span>选择例外休息日</span></el-col>
                </el-row>
                 <el-row>
               <el-col :span="12">
                 <el-date-picker 
               v-model="specialWorkDay" 
                type="date" 
                placeholder="请选择例外工作日" 
                style="width:160px;"
                value-format="yyyy-MM-dd"
                @change="handleWorkDayChange"
                >
                </el-date-picker>
                </el-col>
                   <el-col :span="12">
                     <el-date-picker v-model="specialRestDay" 
                     type="date" 
                     placeholder="请选择例外休息日"  
                     style="width:160px;"
                     value-format="yyyy-MM-dd"
                      @change="handleRestDayChange"
                     >
                     </el-date-picker> 
                     </el-col>
                </el-row>
            <el-row>
               <el-col :span="12"> <span>例外工作日</span></el-col>
                   <el-col :span="12"><span>例外休息日</span></el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-input
                      v-model="temp.specialWorkDays"
                      type="textarea"
                      v-if="false"
                    />
                    <el-tag
                      v-for="tag in workTags"
                      :key="tag.name"
                      closable
                      :type="tag.type"
                      @close="closeWorkTags(tag.name)"
                    >
                      {{ tag.name }}
                    </el-tag>
                  </el-col>
                   <el-col :span="12" style="float:right;">
                     <el-input v-model="temp.specialRestDays"   v-if="false"></el-input>
                    <el-tag
                      v-for="tag in restTags"
                      :key="tag.name"
                      closable
                      :type="tag.type"
                       @close="closeRestTags(tag.name)"
                    >
                      {{ tag.name }}
                    </el-tag>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                   <span>例外工作日备注</span>
                  </el-col>
                  <el-col :span="12">
                    <span>例外休息日备注</span>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                   
                    <el-input
                      v-model="temp.commentWork"
                      type="textarea"
                    />
                  </el-col>
                  <el-col :span="12">
                    <el-input v-model="temp.commentRest" type="textarea" />
                  </el-col>
                </el-row>
               </el-col>
            </el-row>
            <el-form-item label="是否已删除" prop="isdeleted" v-if="false">
              <el-input v-model="temp.isdeleted" />
            </el-form-item>
            <el-form-item label="状态" prop="status" v-if="false">
              <el-input v-model="temp.status" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? ui_create() : ui_update()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
    <router-view></router-view>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import request from "@/utils/request";
import {
  getAll,
  getOne,
  getList,
  create,
  update,
  deleteBatch
} from "@/api/produce/ProduceCalendarApi";

import {
  getAll as getAllCalendarTypes
 
} from "@/api/produce/ProduceCalendarTypeApi";
import moment from "moment";
let that;
export default {
  components: { Pagination },
  data() {
    return {
      filterText: "",
      data2: [],
      defaultProps: {
        children: "children",
        label: "ProduceCalendar"
      },
      list: null,
      list2: null,
      listLoading: true,
      total: 0,
      total2: 0,
      listQuery: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      listQuery2: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      currentProduceCalendarId: 0,
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建"
      },
      rules: {
        calendarName: [
          {
            required: true,
            message: "日历名称不能为空！",
            trigger: "change"
          }
        ],
        calendarTypeId: [
          {
            type: 'number',
            message: "日历类型不能为空！",
            trigger: "change",
            min: 1
          }
        ],
        yearMonth: [
          {
            required: true,
            message: "月份不能为空！",
            trigger: "change"
          }
        ],
        workDays: [
          {
            type: 'number',
            message: "工作日不能为空！",
            trigger: "change",
            min:1
          }
        ],
        workHours: [
          {
            required: true,
            message: "工作日小时不能为空！",
            trigger: "change"
          }
        ],
        customed: [
          {
            required: true,
            message: "是否自定义不能为空！",
            trigger: "change"
          }
        ],
        monday: [
          {
            required: true,
            message: "周一不能为空！",
            trigger: "change"
          }
        ],
        tuesday: [
          {
            required: true,
            message: "周二不能为空！",
            trigger: "change"
          }
        ],
        wensday: [
          {
            required: true,
            message: "周三不能为空！",
            trigger: "change"
          }
        ],
        thursday: [
          {
            required: true,
            message: "周四不能为空！",
            trigger: "change"
          }
        ],
        friday: [
          {
            required: true,
            message: "周五不能为空！",
            trigger: "change"
          }
        ],
        saturday: [
          {
            required: true,
            message: "周六不能为空！",
            trigger: "change"
          }
        ],
        sunday: [
          {
            required: true,
            message: "周天不能为空！",
            trigger: "change"
          }
        ],
        specialWorkDays: [
          {
            required: true,
            message: "例外工作日不能为空！",
            trigger: "change"
          }
        ],
        commentWork: [
          {
            required: true,
            message: "例外工作日备注不能为空！",
            trigger: "change"
          }
        ],
        specialRestDays: [
          {
            required: true,
            message: "例外休息日不能为空！",
            trigger: "change"
          }
        ],
        commentRest: [
          {
            required: true,
            message: "例外休息日备注不能为空！",
            trigger: "change"
          }
        ],
        isdeleted: [
          {
            required: true,
            message: "是否已删除不能为空！",
            trigger: "change"
          }
        ],
        status: [
          {
            required: true,
            message: "状态不能为空！",
            trigger: "change"
          }
        ]
      },
      temp: {
        id: 0,
        calendarName: "",
        calendarTypeId: 0,
        yearMonth:  moment(new Date()).format("YYYY-MM"),
        workDays: 0,
        workHours: "",
        customed: false,
        monday: 0,
        tuesday: 0,
        wensday: 0,
        thursday: 0,
        friday: 0,
        saturday: 0,
        sunday: 0,
        specialWorkDays: "",
        commentWork: "",
        specialRestDays: "",
        commentRest: "",
        isdeleted: false,
        status: 0
      },
      //表格變量
      lstSelected: [],
      value: new Date(),
      workTags: [
      ],
      restTags: [
      ],
      ddCalendarTypes: [],
      ddWorkDays:[{label:"请选择",value: 0},
                  {label:"周一到周五",value: 1},
                  {label:"周一到周六",value: 2},
                  {label:"周一到周日",value: 3}],
      specialWorkDay:"",
      specialRestDay:"",

    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val);
    }
  },
  beforeCreate(){
    that = this
  },
  filters:{
    workdays:function (params) {
        let itm = that.ddWorkDays.filter(v=>v.value == params);
        if(itm != null && itm.length> 0)
        {
          return itm[0].label;
        }
        return "";
    },
   
  },
  created() {
    this.fetchData();
    this.getAllCalendarTypes();
  },
  methods: {
    handleSelectionChange(val) {
      this.lstSelected = val;
      this.value = val[0].yearMonth;
      this.workTags.splice(0);
       this.temp = Object.assign({}, this.lstSelected[0]); // copy obj
      this.temp.specialWorkDays.split(',').forEach(v=>{
        if(v.length> 0)
        {
         this.workTags.push({name:v,type:""});
        }
      })
       this.restTags.splice(0);
      this.temp.specialRestDays.split(',').forEach(v=>{
         if(v.length> 0)
        {
         this.restTags.push({name:v,type:""});
        }
      })
    },
    fetchData() {
      this.listLoading = true;
      let params = {
        name: "",
        page: this.listQuery.page,
        size: this.listQuery.limit
      };
      getList(params).then(response => {
        this.list = response.data.records;
        this.listLoading = false;
        this.total = response.data.total;
      });
    },

    rowClick(row, column, event) {
      this.currentTherbligsTypeId = row.id;
      //this.getTherbligs()
    },
    ui_create() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.temp.id = 0; //自增
          create(this.temp).then(() => {
            this.list.unshift(this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "添加成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_update() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          update(this.temp).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id);
            this.list.splice(index, 1, this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_delete(row, index) {
      if (this.lstSelected == null || this.lstSelected.length === 0) {
        this.$message.error("请先选择要删除的生产日历");
        return;
      }
       this.$confirm('是否要删除该菜单', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
      let ids = [];
      this.lstSelected.map(function(elm) {
        ids.push(elm.id);
      });
      deleteBatch(ids).then(() => {
        ids.forEach(elm => {
          const index = this.list.findIndex(v => v.id === elm);
          this.list.splice(index, 1);
        });

        this.dialogFormVisible = false;
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000
        });
      });
        });
    },
    resetTemp() {
      this.temp = {
         id: 0,
        calendarName: "",
        calendarTypeId: 0,
        yearMonth: "",
        workDays: 0,
        workHours: "",
        customed: false,
        monday: 0,
        tuesday: 0,
        wensday: 0,
        thursday: 0,
        friday: 0,
        saturday: 0,
        sunday: 0,
        specialWorkDays: "",
        commentWork: "",
        specialRestDays: "",
        commentRest: "",
        isdeleted: false,
        status: 0
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleUpdate() {
      if (this.lstSelected == null || this.lstSelected.length !== 1) {
        this.$message.error("请先选择一条ProduceCalendar");
        return;
      }
      this.temp = Object.assign({}, this.lstSelected[0]); // copy obj
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
      
    },
    handleCustomed()
    {
       this.temp.customed = !this.temp.customed;
    },
    getAllCalendarTypes()
    {
       getAllCalendarTypes().then(response=>{
         var result = response.data;
         if(result != null && result.length> 0)
         {
            result.map(v=> {
                this.ddCalendarTypes.push({ label:v.calendarTypeName,value:v.id});
            })
         }
         this.ddCalendarTypes.splice(0,0,{label:"请选择",value: 0});
       })
    },
    handleWorkDayChange(val)
    {
         this.$confirm('确定要添加吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                closeOnClickModal: false,
                type: 'info',
                center: true
            }).then( () => {
                this.workTags.push({name:val,type:"warning"});
                this.temp.specialWorkDays += val + ","; 
            })
    },
     handleRestDayChange(val)
    {
         this.$confirm('确定要添加吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                closeOnClickModal: false,
                type: 'info',
                center: true
            }).then( () => {
                 this.restTags.push({name:val,type:"success"});
                 this.temp.specialRestDays += val + ",";
            })
    },
    closeWorkTags(val)
    {
        const index = this.workTags.findIndex(v => v.name === val);
        this.workTags.splice(index, 1);
        this.temp.specialWorkDays = this.temp.specialWorkDays.replace(val+",","");
    },
    closeRestTags(val)
    {
       const index = this.restTags.findIndex(v => v.name === val);
       this.restTags.splice(index, 1);
       this.temp.specialRestDays = this.temp.specialRestDays.replace(val+",","");
       console.log(this.temp.specialRestDays);
    },
    special(para)
    {
        let index = this.workTags.findIndex(v=> v.name == para);
        if(index > -1){
          return 1;  //workdays 
        }
        index = this.restTags.findIndex(v=> v.name == para);
        if(index > -1){
          return 2;  //restdays 
        }
    }
  }
};
</script>
<style scoped>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  };
  text-align:center;
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
.wrapperSon {
  display: flex;
  justify-content: start;
  align-items: center;
  flex-wrap: wrap;
}
.el-input {
  width: 100px;
}
 /deep/ .el-card__body {
    padding: 0px 0px 0px 0px;
  }
 /deep/ .el-calendar-table .el-calendar-day {
        text-align: center;
    }
.budge{
        width: 10px;
        height: 10px;
        border-radius: 5px;
        margin: 5px auto;
    }
.red{
    background-color: #c9413f;
}
.green{
    background-color: #25b591;
}
.orange{
    background-color: #ee915c;
}
</style>
